import React, { Suspense, useEffect, useMemo, useState } from 'react';
import { Layout, Menu, Typography } from 'antd';

// import AppPermissionContent from '@/pages/app-permission-manage/components/AppPermissionContent';
const AppPermissionContent = React.lazy(
  () => import('@/pages/app-permission-manage/components/AppPermissionContent'),
);

import {
  useApiFlag,
  useConfigActions,
  useDatasetFlag,
  useInitializeData,
  useManagePage,
} from '@/store/configStore';

import { useRouter } from '@/router/hooks';

import useWindowWidth from '@/hooks/event/use-window-width';
const { Text } = Typography;

import { useTranslation } from 'react-i18next';
import { SvgIcon } from '@/components/icon';
import './permission.scss';

import usePermission from '@/hooks/event/usePermission';

const { Content, Sider } = Layout;

import { useRoleManage } from '@/store/roleManageStore';
// import SharelinkPage from '@/pages/share-link-manage';

const SharelinkPage = React.lazy(() => import('@/pages/share-link-manage'));
const QaPermission = React.lazy(() => import('@/pages/qa-permission'));

import { useUserInfo } from '@/store/userStore';
import { LicenseEditionEnum } from '@/common';
import { useLocation } from 'react-router-dom';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import { CircleLoading } from '@/components/loading';
import { AppType } from '@/common/app/constants';

// 定义组件接受的属性类型
interface AppPageProps {
  subPage?: 'permission' | 'user' | 'role' | 'share' | 'qaPermission';
  onPageChange?: (page: 'permission' | 'user' | 'role' | 'share' | 'qaPermission') => void;
}

const AppPage: React.FC<AppPageProps> = ({ subPage, onPageChange }) => {
  const router = useRouter();
  const [selectedKey, setSelectedKey] = useState<string>(subPage || 'qaPermission');
  const { isPc } = useWindowWidth();
  const { t } = useTranslation();

  const initializeData = useInitializeData();
  const { fetchInitialInfo } = useConfigActions();

  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const appId = queryParams.get('appId') || '';
  // const isPreview = queryParams.get('preview') === 'true';
  const { isPreview, createUserId, appDetail } = useOrchestrationStore();

  const userInfo = useUserInfo();
  const loginUserId = userInfo?._id || userInfo?.id;
  const isRoot = userInfo?.username == 'root';

  const enable_permission_share = useMemo(() => {
    return initializeData?.license_edition != LicenseEditionEnum.basic &&
      initializeData?.enable_permission_share !== undefined
      ? initializeData.enable_permission_share
      : false;
  }, [initializeData]);

  useEffect(() => {
    fetchInitialInfo();
  }, [fetchInitialInfo]);

  // 响应外部subPage属性变化
  useEffect(() => {
    if (subPage) {
      setSelectedKey(subPage);
    }
  }, [subPage]);

  // 处理URL参数
  useEffect(() => {
    const searchParams = new URLSearchParams(location.search);
    const appParam = searchParams.get('app');
    if (
      appParam &&
      (appParam === 'permission' ||
        appParam === 'user' ||
        appParam === 'role' ||
        appParam === 'share' ||
        appParam === 'qaPermission')
    ) {
      setSelectedKey(appParam);
    }
  }, [location.search]);

  // 处理菜单点击
  const handleMenuClick = (e: { key: string }) => {
    const key = e.key as 'permission' | 'user' | 'role' | 'share' | 'qaPermission';
    setSelectedKey(key);

    // 通知父组件页面变更
    if (onPageChange) {
      onPageChange(key);
    }
  };

  const getContentComponent = () => {
    switch (selectedKey) {
      case 'permission':
        // return <Permission />;
        return (
          <div
            className="mx-2 w-full"
            style={{
              height: 'calc(-80px + 100vh)',
            }}
          >
            <AppPermissionContent
              appId={appId}
              isPreview={isPreview}
              createUserId={{ create_user_id: createUserId }}
              isPermissions={loginUserId != createUserId && !isRoot}
            />
          </div>
        );
      // case 'user':
      //   return <UserManager />;
      // case 'role':
      //   return <RoleManager />;
      case 'share':
        return (
          <div
            className=" mx-2 w-full rounded-xl"
            style={{
              height: 'calc(-80px + 100vh)',
            }}
          >
            <SharelinkPage />
          </div>
        );
      case 'qaPermission':
        return (
          <div
            className=" mx-2 w-full rounded-xl"
            style={{
              height: 'calc(-80px + 100vh)',
            }}
          >
            <QaPermission />
          </div>
        );
      default:
        return null;
    }
  };

  return (
    <Layout
      className="[-ms-overflow-style:none] [scrollbar-width:none]"
      style={{ overflowX: 'hidden', height: '100vh' }}
    >
      <Layout>
        {true && (
          <>
            <Sider
              width={true ? 260 : '100%'}
              className="!rounded-[12px]"
              style={{
                background: '#FFF',
                display: 'flex',
                flexDirection: 'column',
                // borderInlineEnd: '1px solid rgba(13, 75, 255, 0.13)',
                // height: 'calc(100% - 32px)',
                height: 'calc(-80px + 100vh)',
              }}
            >
              <Menu
                style={{
                  padding: '10px',
                  borderRadius: '12px',
                  borderInlineEnd: 'unset',
                }}
                mode="vertical"
                selectedKeys={true ? [selectedKey] : []}
                onClick={handleMenuClick}
                className="permission-menu"
              >
                <Menu.Item key="qaPermission">
                  <div className="flex items-center pl-3">
                    <SvgIcon
                      // icon="fluent-mdl2--permissions-solid"
                      icon="ai-orch-qa-permission"
                      size={20}
                      // style={{
                      //   borderRadius: '12px',
                      //   padding: '3px',
                      // }}
                    />
                    <div className="pl-2">问答与知识库权限</div>
                  </div>
                </Menu.Item>
                {appDetail?.appType != AppType.fusion && (
                  <Menu.Item key="permission">
                    <div className="flex items-center pl-3">
                      <SvgIcon
                        // icon="fluent-mdl2--permissions-solid"
                        icon="menu_data"
                        size={20}
                        // style={{
                        //   borderRadius: '12px',
                        //   padding: '3px',
                        // }}
                      />
                      <div className="pl-2">人员配置</div>
                    </div>
                  </Menu.Item>
                )}
                {/* {appDetail?.appType != AppType.fusion && (
                  <Menu.Item key="share">
                    <div className="flex items-center pl-3">
                      <SvgIcon
                        // icon="share"
                        icon="menu_share"
                        size={20}
                        // style={{
                        //   borderRadius: '12px',
                        //   padding: '3px',
                        // }}
                      />
                      <div className="pl-2">分享链接</div>
                    </div>
                  </Menu.Item>
                )} */}
              </Menu>
            </Sider>
            <Content
              className="rounded-md"
              style={{
                height: 'calc(100vh - 64px)',
                overflow: 'auto',
              }}
            >
              <Suspense fallback={<CircleLoading />}>{getContentComponent()}</Suspense>
            </Content>
          </>
        )}
      </Layout>
    </Layout>
  );
};

export default AppPage;
